var setting = {
    check: {
        enable: true,
        autoCheckTrigger: true,
        chkStyle : "checkbox"
    },
    view: {
        showIcon: false
    },
    data: {
        simpleData: {
            enable: true
        }
    }
};
var zNodes ;
// console.info("zNodes:"+zNodes);
function setCheck() {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    zTree.setting.check.chkboxType = {"Y": 'ps', "N": 'ps'};
}
function searchNode(){
    var ztree = $.fn.zTree.getZTreeObj("treeDemo");
    var keywords=$("input[name='keyword']").val();
    if (keywords.length>0) {
        var nodes = ztree.transformToArray(ztree.getNodes());
        ztree.hideNodes(nodes);//隐藏所有节点
        var nodeList = ztree.getNodesByParamFuzzy("name", keywords, null);//模糊查询
        if (nodeList && nodeList.length > 0) {
            for ( var i = 0; i < nodeList.length; i++) {
                nodeList[i].highlight = true;//设置高亮
                findParent(ztree, nodeList[i]);
                ztree.updateNode(nodeList[i]);
                ztree.expandNode(nodeList[i], true, true, false);//展开节点
            }
        }
    }else{
       // layer.open({
       //     title:'提示',
       //     type: 1,
       //     area: ['300px', '200px'],
       //     shadeClose: true, //点击遮罩关闭
       //     content: '<div style="padding:20px;text-align:center;font-size: 14px;color:#DE5246"><p>请输入角色名称</p></div>',
       //});
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
    }
}
//找到其父亲节点
function findParent(ztree, node) {
    ztree.expandNode(node, true, false, true);//展开节点
    ztree.showNode(node);//显示该节点
    var pNode = node.getParentNode();
    if (pNode != null) {
        findParent(ztree, pNode);
    }
}
//设置字体颜色
function setFontCss(treeId, treeNode) {
    if (treeNode.id === 1) {//根节点
        return {
            color : "black"
        };
    }
    if (treeNode.highlight) {//如果符合模糊查询条件则高亮显示
        return {
            color : "red"
        };
    }else{
        return {
            color : "black"
        };
    }
}
$(document).ready(function(){
    // console.info('type'+typeof(zNodes));
    // console.info('zNodes:'+JSON.stringify(zNodes));
    if(typeof(zNodes)==='undefined'){
        var roleId = $("#roleId").val();
        // alert('roleId'+$("#roleId").val());
        $.get("/admin/getOrgListByRoleId",{"roleId":roleId},function(data,status){
            if(status){
                zNodes = data;
                // console.info('type'+typeof(zNodes));
                // console.info('data:'+JSON.stringify(zNodes));
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                setCheck();

                /*全选*/
                $('.all-select').on('click',function(){
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    if($(this).is(':checked')){
                        zTree.checkAllNodes(true);
                    }else{
                        zTree.checkAllNodes(false);
                    }
                });
                /*提交*/
                $('.submitBtn').on('click',function(){


                    var roleId = $("#roleId").val();
                    var roleName = $("#roleName").val();
                    var params = {};
                    if(roleName===''){
                        alert("角色名称不能为空!");
                        return;
                    }
                    params.roleName = roleName;
                    params.roleId = roleId;
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    var nodes = zTree.getCheckedNodes(true);
                    if (nodes.length === 0) {
                        layer.open({
                            title:'提示',
                            type: 1,
                            area: ['300px', '200px'],
                            shadeClose: true, //点击遮罩关闭
                            content: '<div style="padding:20px;text-align:center;font-size: 14px;color:#DE5246"><p>请选择选择一个节点</p></div>'
                        });
                    }else{
                        var nodesArray = [];
                        for(var i=0;i<nodes.length;i++){
                            var nodeJson = {};
                            if(nodes[i].level === 0){
                                if(nodes[i].check_Child_State === 1){
                                    var children = nodes[i].children;
                                    for(var j=0;j<children.length;j++){
                                        if(children[j].checked){
                                            var childNode = {};
                                            childNode.id = children[j].id;
                                            childNode.pId = children[j].pId;
                                            childNode.level = 2;
                                            nodesArray.push(childNode);
                                        }
                                    }
                                }else{
                                    nodeJson.id = nodes[i].id;
                                    nodeJson.pId = nodes[i].pId;
                                    nodeJson.level = 1;
                                    nodesArray.push(nodeJson);
                                }
                            }
                        }
                        params.nodesArray = nodesArray;
                        // console.log("params:"+JSON.stringify(params));
                        $.ajax({
                            type: "POST",
                            url: "/admin/editRole",
                            data: JSON.stringify(params),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data) {

                                if(data.status){
                                    layer.open({
                                        title:'提示',
                                        type: 1,
                                        area: ['300px', '200px'],
                                        shadeClose: true, //点击遮罩关闭
                                        content: '<div style="padding:20px;"><p>修改成功!</p></div>',
                                        btn:['确定','取消'],
                                        yes: function(index){
                                            layer.close(index); //如果设定了yes回调，需进行手工关闭
                                            window.location.href ='/admin/roleList';
                                        }
                                    });

                                }else{
                                    alert(data.message);
                                }
                            }
                        });
                    }
                });
                /*取消*/
                $('.cancelBtn').on('click',function(){
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.checkAllNodes(false);
                    $('.all-select').removeAttr("checked");
                    $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                    $("input[name='keyword']").val('');//搜索框重置
                });
                /*搜索节点*/
                $("input[name='keyword']").on('blur',function(){
                    searchNode();
                })
            }
        });
    }

});